package cmj.cloudmusic.activity;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.musicmodule.PlayApplication;
import com.example.musicmodule.constants.Constants;
import com.example.musicmodule.entity.Music;
import com.example.musicmodule.ible.IMain;
import com.example.musicmodule.ible.IMusic;
import com.example.musicmodule.service.PlayService;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import cmj.cloudmusic.R;
import cmj.cloudmusic.UI.CircleImage;
import cmj.cloudmusic.fragment.Main_Fragment;
import cmj.cloudmusic.fragment.MyLocalSongListFragment;
import cmj.cloudmusic.fragment.TodayMusicFragment;

public class MainActivity extends AppCompatActivity implements Fragment_Activity,View.OnClickListener,IMain {
    private int TIME=1000;
    private long backTime;

    private PlayApplication playApplication;
    private IMusic music;
    private Intent intent;
    private FrameLayout fragcontainter;
    AudioManager audio;

    public  FragmentManager fm;
    public FragmentTransaction ft;

    private Main_Fragment mainfragment;
    private TodayMusicFragment toddayfragment;
    private MyLocalSongListFragment localSongFragment;

    public DrawerLayout drawerLayout;
    public RelativeLayout left_drawer;

    //通知栏

    Notification notification;
    RemoteViews remoteViews;

    //侧滑栏
    private CircleImage headimg;
    private TextView name;

    //面板

    private LinearLayout playbar;

    private ImageView musicimg;
    private TextView musicname;
    private TextView singer;
    private ImageButton playstop;
    private ImageButton next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        //设置状态栏透明 在setcontentView之前
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //清除标记   透明状态栏 和  透明导航（华为控制按钮）
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(
                    //设置充满屏幕
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    //隐藏导航栏
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            );
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏透明
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        }

        setContentView(R.layout.activity_main);

        playApplication= (PlayApplication) getApplication();
        playApplication.mm=this;
        initService();

        drawerLayout= (DrawerLayout) findViewById(R.id.drawer);
        initMainView();
        updatePlayBar();
        replace("main");
    }
// 初始化控件
    private void initMainView(){
         audio = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        fm=getSupportFragmentManager();

        left_drawer= (RelativeLayout) findViewById(R.id.left_draw);

        headimg= (CircleImage) findViewById(R.id.headimg);
        name= (TextView) findViewById(R.id.name);


        playbar= (LinearLayout) findViewById(R.id.playmodel);

        musicimg= (ImageView) findViewById(R.id.musicimg);
        musicname= (TextView) findViewById(R.id.musicname);
        singer= (TextView) findViewById(R.id.singer);
        playstop= (ImageButton) findViewById(R.id.play);
        next= (ImageButton) findViewById(R.id.next);


        playbar.setOnClickListener(this);
        playstop.setOnClickListener(this);
        next.setOnClickListener(this);
    }




    /**
     * 绑定服务
     */
    private void initService() {
        intent=new Intent(this, PlayService.class);
        startService(intent);
        bindService(intent,connection,BIND_AUTO_CREATE);
    }

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playApplication.music=(PlayService.PlayBinder)service;
            music=playApplication.music;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };




//    //监听返回键， 双击退出
//    @Override
//    public void onBackPressed() {
//        if (System. currentTimeMillis ()- backTime > TIME ){
//            Toast. makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
//            backTime =System. currentTimeMillis ();
//        } else {
//            super .onBackPressed();
//        }
//
//    }


    /**
     * 控制fragment的显示
     * @param tag
     */
    @Override
    public void replace(String tag) {
        switch (tag){
            case "main":
                ft=fm.beginTransaction();
                if (mainfragment==null){
                    mainfragment=new Main_Fragment();
                    ft.add(R.id.fragement,mainfragment);
                }

                if (toddayfragment!=null){
                    ft.hide(toddayfragment);
                }
                if (localSongFragment!=null){
                    ft.hide(localSongFragment);
                }
                ft.show(mainfragment)
                .commit();
                break;
            case "today":
                ft=fm.beginTransaction();
                if (toddayfragment==null){
                    toddayfragment=new TodayMusicFragment();
                }
                ft.add(R.id.fragement,toddayfragment)
                        .addToBackStack(null);
                if (localSongFragment!=null){
                    ft.hide(localSongFragment);
                }
                    ft.show(toddayfragment)
                      .hide(mainfragment)
                      .commit();
                break;
            case "local":
                ft=fm.beginTransaction();
                if (localSongFragment==null){
                    localSongFragment=new MyLocalSongListFragment();
                }
                ft.add(R.id.fragement,localSongFragment)
                        .addToBackStack(null);
                if (toddayfragment!=null){
                    ft.hide(toddayfragment);
                }
                    ft.show(localSongFragment)
                      .hide(mainfragment)
                      .commit();
                break;

        }
    }

    /**
     * 解绑服务
     */
    @Override
    protected void onDestroy() {
        unbindService(connection);
        playApplication.mm=null;
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.playmodel:
                Intent intent=new Intent(this,PlayActivity.class);
                startActivity(intent);
                if (playApplication.iPlayer!=null){
                    playApplication.iPlayer.update();
                }
                break;
            case R.id.play:
                if (music.isPlay()){
                    playstop.setImageResource(R.drawable.playbar_btn_play);
                }else {
                    playstop.setImageResource(R.drawable.playbar_btn_pause);
                }
                music.pause();
                break;
            case R.id.next:
                music.next();
                break;
        }
    }

    /**
     * 通知栏面板
     */
    @Override
    public void initNotification(final Music music){

        remoteViews=new RemoteViews(getPackageName(),R.layout.notifiction_music_playbar);
         notification=new Notification.Builder(this)
                .setSmallIcon(R.mipmap.minlogo)
                .setContent(remoteViews)
                .build();

////        remoteViews.setImageViewUri(R.id.musicimg, Uri.parse(music.getUrl()));
//        final Handler handler=new Handler(){
//            @Override
//            public void handleMessage(Message msg) {
//                Bitmap bitmap= (Bitmap) msg.obj;
//                remoteViews.setImageViewBitmap(R.id.musicimg,bitmap);
//                playApplication.notiManager.notify(Constants.PLAY_NOTI,notification);
//            }
//        };
//        Thread thread=new Thread(){
//            @Override
//            public void run() {
//                try {
//                    URL url=new URL(music.getUrl());
//                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
//                    connection.connect();
//                    InputStream is=connection.getInputStream();
//                    byte[] data=readStream(is);
//
//                    YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 200,200, null);//20、20分别是图的宽度与高度
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    yuvimage.compressToJpeg(new Rect(0, 0,200,200), 100, baos);//80--JPG图片的质量[0-100],100最高
//                    byte[] jdata = baos.toByteArray();
//                    if(jdata!=null) {
//                        Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
//                        Message msg=new Message();
//                        msg.obj=bitmap;
//                        handler.sendMessage(msg);
//                    }
//                    is.close();
//                    baos.close();
//
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//        thread.start();

        if (playApplication.music.isPlay()){
            remoteViews.setImageViewResource(R.id.play,R.drawable.a8s);
        }else {
            remoteViews.setImageViewResource(R.id.play,R.drawable.a8u);
        }

        remoteViews.setTextViewText(R.id.musicname,music.getTitle());

        remoteViews.setTextViewText(R.id.singer,music.getAuthor());

        //给按钮添加绑定广播
        Intent playIntent=new Intent("com.jereh.music.play");
        PendingIntent playPending=PendingIntent.getBroadcast(this,0,playIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(com.example.musicmodule.R.id.play,playPending);

        Intent nextIntent=new Intent("com.jereh.music.next");
        PendingIntent nextPending=PendingIntent.getBroadcast(this,0,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(com.example.musicmodule.R.id.next,nextPending);

        Intent prevIntent=new Intent("com.jereh.music.prev");
        PendingIntent prevPending=PendingIntent.getBroadcast(this,0,prevIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(com.example.musicmodule.R.id.prev,prevPending);


        playApplication.notiManager.notify(Constants.PLAY_NOTI,notification);
    }

    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }

        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }


    @Override
    public void notificationPlayStop(){
        if (remoteViews!=null){
            if (playApplication.music.isPlay()){
                remoteViews.setImageViewResource(R.id.play,R.drawable.a8s);
            }else {
                remoteViews.setImageViewResource(R.id.play,R.drawable.a8u);
            }
            playApplication.notiManager.notify(Constants.PLAY_NOTI,notification);
        }
    }
    /**
     *  刷新播放面板
     */
    @Override
    public  void updatePlayBar(){
        if (playApplication.music!=null){
            playbar.setVisibility(View.VISIBLE);
        }else {
            playbar.setVisibility(View.GONE);
            return;
        }
        if (playApplication.music.isPlay()){
            playstop.setImageResource(R.drawable.playbar_btn_pause);
        }else {
            playstop.setImageResource(R.drawable.playbar_btn_play);
        }
        if (playApplication.songList.size()>0) {
            String imgurl = playApplication.songList.get(playApplication.songPosition).getPic_small();
            String name = playApplication.songList.get(playApplication.songPosition).getTitle();
            String singer1 = playApplication.songList.get(playApplication.songPosition).getAuthor();
            Glide.with(this).load(imgurl).placeholder(R.drawable.sd).error(R.drawable.se).into(musicimg);
            musicname.setText(name);
            singer.setText(singer1);
        }

    }

    public void showFragment(Fragment f){
        ft=fm.beginTransaction();
        if (mainfragment!=null){
            ft.hide(mainfragment);
        }

        if (toddayfragment!=null){
            ft.hide(toddayfragment);
        }
        if (localSongFragment!=null){
            ft.hide(localSongFragment);
        }

        ft.add(R.id.fragement,f).addToBackStack(null);
        ft.show(f)
                .commit();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                audio.adjustStreamVolume(
                        AudioManager.STREAM_MUSIC,
                        AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }
}
